/*
 * ExecutableFileFieldEditor.java
 * 
 * Copyright 2007 Kamen Petroff.
 * All Rights Reserved.
 * 
 * This software is the proprietary information of Kamen Petroff.
 * Use is subject to license terms.
 * 
 * Created on Mar 3, 2007 at 2:32:47 PM by Kamen Petroff
 */
package com.google.code.shell4eclipse.preferences;

import java.io.File;
import java.util.StringTokenizer;

import org.eclipse.jface.preference.FileFieldEditor;
import org.eclipse.swt.widgets.Composite;

/**
 * 
 *
 * @author Kamen Petroff 
 * @since Mar 3, 2007
 */
public class ExecutableFileFieldEditor extends FileFieldEditor {

	public ExecutableFileFieldEditor(String name, String labelText, Composite parent) {
		super(name, labelText, true, parent);
		super.setEmptyStringAllowed(false);
	}
	
	@Override
	public void setEmptyStringAllowed(boolean allowEmptyString) {
		if(allowEmptyString) {
			throw new IllegalArgumentException("Empty file names are not allowed!");
		}
	}

	@Override
	protected boolean checkState() {

        String path = getTextControl().getText();
        if (path != null) {
			path = path.trim();
		} else {
			showErrorMessage("File path cannot be empty");
			return false;
		}
        
        File file = findInPath(path);
        if(file == null) {
        	if(new File(path).isAbsolute()) {
        		showErrorMessage("File does not exist!");
        	} else {
        		showErrorMessage("Can't find file in path!");
        	}
			return false;
        }

        // OK!
        clearErrorMessage();
        return true;
	}

	private File findInPath(String path) {
		File file = new File(path);
		if(file.isAbsolute()) {
			if (file.exists() && file.isFile()) {
				return file;
			} else {
				return null;
			}
		}
		StringTokenizer tokenizer = new StringTokenizer(System.getenv("PATH"), File.pathSeparator);
		while(tokenizer.hasMoreTokens()) {
			String dir = tokenizer.nextToken();
			file = new File(dir, path);
			if(file.exists() && file.isFile()) {
				return file;
			}
		}
		return null;
	}
}
